# coding: utf-8
from time import sleep

from loguru import logger
from requests import request, HTTPError

from .settings import UserAgent, BaseUrl
from .signal_bus import signalBus


def raise_for_status(status_code: int):
    if status_code == 401:
        signalBus.tokenInvalidSignal.emit()
        raise HTTPError('令牌过期')
    elif status_code == 403:
        raise HTTPError('禁止访问')
    elif status_code == 404:
        raise HTTPError('没有找到页面')
    elif status_code == 405:
        raise HTTPError('不允许使用该方法')
    elif status_code == 408:
        raise HTTPError('请求超时')
    elif status_code == 413:
        raise HTTPError('请求实体过大')
    elif status_code == 414:
        raise HTTPError('请求URI过长')
    elif status_code == 415:
        raise HTTPError('不支持的媒体类型')
    elif status_code == 429:
        raise HTTPError('请求过于频繁')
    elif status_code == 500:
        raise HTTPError('服务器内部错误')
    elif status_code == 502:
        raise HTTPError('网关错误')
    elif status_code == 503:
        raise HTTPError('服务不可用')
    elif status_code == 504:
        raise HTTPError('网关超时')


class BaseAPI:
    base_url = BaseUrl

    @classmethod
    def send(cls, method: str, url: str, **kwargs):
        headers = kwargs.get('headers', {})
        headers.update({'User-Agent': UserAgent})
        kwargs.update({'headers': headers})
        isAdd = kwargs.pop('isAdd', True)
        if isAdd:
            url = cls.base_url + url
        logger.debug(f'发送请求：url={url}, method={method}, kwargs={kwargs}')
        response = request(method, url, **kwargs, allow_redirects=True, timeout=10)
        logger.debug(f'请求成功：url={url}, method={method}, status_code={response.status_code}')
        raise_for_status(response.status_code)
        response.raise_for_status()
        return response

    @classmethod
    def get(cls, url, **kwargs):
        return cls.send('GET', url, **kwargs)

    @classmethod
    def post(cls, url, **kwargs):
        return cls.send('POST', url, **kwargs)

    @classmethod
    def put(cls, url, **kwargs):
        return cls.send('PUT', url, **kwargs)

    @classmethod
    def delete(cls, url, **kwargs):
        return cls.send('DELETE', url, **kwargs)
